package com.shuiyun.jtt.session;

import cn.hutool.core.util.ObjectUtil;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.shuiyun.jtt.utils.CacheKey;
import io.netty.channel.Channel;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author yezhihao
 * home https://gitee.com/yezhihao/jt808-server
 */
@Component
public class SessionManager {

    private Map<Object, Session> sessionMap;

    private Cache<Object, Integer> versionCache;


    public SessionManager() {
        this.sessionMap = new ConcurrentHashMap<>();
        this.versionCache = Caffeine.newBuilder().expireAfterWrite(5, TimeUnit.MINUTES).build();
    }

    public Session newSession(Channel channel) {
        return new Session(channel, this);
    }

    public Session get(Object clientId) {
        if (ObjectUtil.isNull(clientId)){
            return null;
        }
        return sessionMap.get(clientId);
    }

    public Collection<Session> all() {
        return sessionMap.values();
    }

    protected void put(Object clientId, Session newSession) {
        Session oldSession = sessionMap.put(clientId, newSession);
    }

    public void putVersion(Object clientId, int version) {
        versionCache.put(clientId, version);
    }

    public Integer getVersion(Object clientId) {
        return versionCache.getIfPresent(clientId);
    }

    public void callSessionDestroyedListener(Session session){
        this.sessionMap.remove(session.getClientId());
        CacheKey.instance.getRegisterDeviceInfoMap().remove(session.getClientId());
    }
}